package com.example.musicplayer

import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.RequiresApi
import java.io.IOException

class MusicService : Service() {
    companion object {
        val Commond = "Operate"
    }

    val TAG = "MusicService"
    val mediaPlayer = MediaPlayer()
    val musicList: MutableList<String> = mutableListOf()
    val musicNameList: MutableList<String> = mutableListOf()
    var current = 0
    var isPause = false
    val binder = MusicBinder()
    private val handler = Handler(Looper.getMainLooper())
    private val updateSeekBarRunnable = object : Runnable {
        override fun run() {
            binder.musicServiceListener?.onPositionChanged(mediaPlayer.currentPosition)
            handler.postDelayed(this, 1000) // 每秒更新一次
        }
    }

    interface MusicServiceListener {
        fun onMusicChanged(musicName: String)
        fun onPositionChanged(position: Int)
    }

    inner class MusicBinder : Binder() {
        var musicServiceListener: MusicServiceListener? = null

        val musicName
            get() = musicNameList.getOrNull(current) ?: "Unknown"

        var currentPosition
            get() = mediaPlayer.currentPosition
            set(value) {
                mediaPlayer.seekTo(value)
                notifyMusicChange()
            }

        val duration
            get() = mediaPlayer.duration // 确保这里是毫秒

        val size
            get() = musicList.size

        val currentIndex
            get() = current // 返回当前歌曲索引
    }

    @SuppressLint("NewApi")
    override fun onCreate() {
        super.onCreate()
        getMusicList()
        mediaPlayer.setOnPreparedListener {
            it.start()
            handler.post(updateSeekBarRunnable) // 开始更新进度条
            notifyMusicChange()
        }
        mediaPlayer.setOnCompletionListener {
            current++
            if (current >= musicList.size) {
                current = 0
            }
            play()
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val operate = intent?.getIntExtra(Commond, 1) ?: 1
        when (operate) {
            1 -> play()
            2 -> Pause()
            3 -> Stop()
            4 -> Next()
            5 -> Prev()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    fun Pause() {
        if (isPause) {
            mediaPlayer.start()
            isPause = false
        } else {
            mediaPlayer.pause()
            isPause = true
        }
        notifyMusicChange()
    }

    fun Next() {
        current++
        if (current >= musicList.size) {
            current = 0
        }
        play()
    }

    fun Stop() {
        mediaPlayer.stop()
        stopSelf()
        handler.removeCallbacks(updateSeekBarRunnable) // 停止更新进度条
    }

    fun Prev() {
        current--
        if (current < 0) {
            current = musicList.size - 1
        }
        play()
    }

    fun play() {
        if (musicList.isEmpty()) return
        val path = musicList[current]
        mediaPlayer.reset()
        try {
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepareAsync()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun notifyMusicChange() {
        binder.musicServiceListener?.onMusicChanged(musicNameList[current])
        binder.musicServiceListener?.onPositionChanged(mediaPlayer.currentPosition)
    }

    override fun onBind(intent: Intent): IBinder {
        return binder
    }

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("Range")
    fun getMusicList() {
        val cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null)
        if (cursor == null) {
            Log.d(TAG, "Cursor is null")
            return
        }
        while (cursor.moveToNext()) {
            val musicPath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
            musicList.add(musicPath)
            val musicName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
            musicNameList.add(musicName)
            Log.d(TAG, "getMusicList: $musicPath name: $musicName")
        }
        cursor.close()
    }
}